<?php


namespace Xy\Rbac\Services;


use Xy\Rbac\Providers\RbacServiceProvider;
use Xy\Rbac\Exceptions\RbacException;
use Xy\Rbac\Models\RbacPowerPageModel;
use Xy\Rbac\Models\RbacRoleModel;
use Xy\Rbac\Repositories\RbacPowerPageRepository;
use Xy\Rbac\Repositories\RbacUserRoleRepository;

class RbacPowerPageService {
    protected $_rbacPowerRepository;
    
    public function __construct(RbacPowerPageRepository $rbacPowerRepository) {
        $this->_rbacPowerRepository = $rbacPowerRepository;
    }
    
    /**
     * @return array
     */
    public function getRabcPowerPage() {
        $dbPowerList = $this->_rbacPowerRepository->getAllPowerPage()->keyBy('id')->toArray();
        
        return [
            [
                'id'       => 0,
                'title'    => '所有',
                'level'    => 0,
                'expand'   => true,
                'children' => $this->_getUserPowerPageTree($dbPowerList),
            ],
        ];
    }
    
    /**
     * @param $request
     *
     * @return mixed
     */
    public function storeRabcPowerPage($request) {
        $dataInfo = $request->post();
        $fillAbel = array_keys($dataInfo);
        
        $noNullField = ['api_uri', 'api_method', 'ext', 'desc'];
        
        foreach ($noNullField as $noNullFieldKey => $noNullFieldVal) {
            is_null($dataInfo[$noNullFieldVal]) && $dataInfo[$noNullFieldVal] = '';
        }
        
        return $this->_rbacPowerRepository->storePowerPage($dataInfo, $fillAbel);
    }
    
    /**
     * @param $id
     *
     * @return array
     * @throws \Exception
     */
    public function destroyRabcPowerPage($id) {
        if ($this->_rbacPowerRepository->getChildrenByPid($id)->isNotEmpty()) {
            throw new RbacException(1140001);
        }
        
        return $this->_rbacPowerRepository->destroyPowerPage($id);
    }
    
    /**
     * @param $id
     * @param $request
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws \Exception
     */
    public function updateRabcPowerPage($id, $request) {
        $dataInfo = $request->input();
        unset($dataInfo['id']);
        $fillAble = array_Keys($dataInfo);
        
        return $this->_rbacPowerRepository->updatePowerPageById($id, $dataInfo, $fillAble);
    }
    
    /**
     * @param array $powerIdList
     *
     * @return array
     */
    protected function _getUserPowerPageTree(array $dbPowerList) {
        //获取所有权限页面
        $navInfo     = [];
        
        //后台左侧导航信息获取
        foreach ($dbPowerList as $dbPowerId => &$dbPowerInfo) {
            //供树状目录展示用
            $dbPowerInfo['label'] = $dbPowerInfo['title'];
            
            if ($dbPowerInfo['pid'] && isset($dbPowerList[$dbPowerInfo['pid']])) {
                $dbPowerList[$dbPowerInfo['pid']]['children'][] = &$dbPowerInfo;
            }
            
            if ($dbPowerInfo['pid'] == 0) {
                $navInfo[$dbPowerId] = &$dbPowerInfo;
            }
        }
        
        return array_values($navInfo);
    }
    
    /**
     * 当前登录用户权限获取
     * @return array
     */
    public function getUserPermission() {
        $userId      = RbacServiceProvider::getUserId();
        $userRoleCol = RbacUserRoleRepository::getInstance()->getRoleByUserId($userId, ['role']);
        
        $userRoleIdList = $userRoleCol->pluck('role_id')->toArray();
        
        if (in_array(RbacRoleModel::SUPER_USER_ROLE_ID, $userRoleIdList)) {
            $powerPageList = $this->_rbacPowerRepository
                ->getAllPowerPage(function ($query) {
                    $query->where('status', RbacPowerPageModel::STATUS_YES)
                        ->where('level', '!=', RbacPowerPageModel::LEVEL_API);
                })
                ->keyBy('id')
                ->toArray();
        } else {
            $powerIdList = [];
            foreach ($userRoleCol as $userRoleIndex => $userRoleEl) {
                if ($userRoleEl->role) {
                    $rolePowerList = $userRoleEl->role->power;
                    $powerIdList   = array_merge($powerIdList, $rolePowerList);
                }
            }
            
            $powerIdList   = array_unique($powerIdList);
            $powerPageList = RbacPowerPageRepository::getInstance()
                ->getPowerPageByIdList($powerIdList, function ($query) {
                    $query->orderBy('order')
                        ->where('level', '!=', RbacPowerPageModel::LEVEL_API);
                })
                ->keyBy('id')
                ->toArray();
        }
        
        return $this->_getUserPowerPageTree($powerPageList);
    }
}